package com.vecharm.app.ui.smartlable


import android.support.v7.app.AlertDialog
import android.util.Log
import com.ling.sdk.app.ActivityStack
import com.ling.sdk.ui.BaseFragment
import com.vecharm.app.R
import com.vecharm.app.manager.VideoCacheManager
import com.vecharm.app.wiget.IPayer
import com.vecharm.app.wiget.PLPlayer
import kotlinx.android.synthetic.main.fragment_video.*

typealias AfterActions = ArrayList<() -> Unit>

class VideoFragment : BaseFragment(), IAction {
    override fun preload(urls: ArrayList<String>?) {
        urls?.forEach { VideoCacheManager.cache(it) }
    }

    override fun onStartPlay() {
        if (player == null) {
            afterActions.add { player?.play() }
        } else
            player?.play()
    }

    override fun onPausePlay() {
        player?.pause()
    }


    override fun onActivityResume() {
        player?.onResume()
    }

    override fun onActivityPause() {
        player?.onPause()
    }

    override fun getLayoutId() = R.layout.fragment_video

    private val messageAlertDialog = lazy { AlertDialog.Builder(ActivityStack.getTopActivity()).setNegativeButton("确定", null).create() }

    private var player: IPayer? = null
    private var url = ""
    private val afterActions = AfterActions()

    override fun onInitView() {
        url = arguments?.getStringArrayList("list")?.getOrNull(0) ?: ""
        initPlayer()
    }

    private fun initPlayer() {
        Log.e("VideoFragment", "initPlayer")
        player = PLPlayer()

        player?.setOnErrorListener {
            messageAlertDialog.value.setMessage(it)
            messageAlertDialog.value.show()
        }
        val newUrl = VideoCacheManager.getProxyUrl(url)
        player?.initPlayer(videoRootView, newUrl)

        afterActions.forEach { it.invoke() }
        afterActions.clear()

    }

    private fun close() {
        player?.stop()
        player = null
    }


    override fun onDestroyView() {
        super.onDestroyView()
        close()
    }


}
